import org.apache.http.HttpException;
import DTO.userinfomation;
import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
@WebServlet("/login_servlet")
public class login_servlet extends HttpServlet {
    public void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException {
        doGet(req,resp);
    }
    public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException{
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String string =null;
        int flag=0;
        String img = "default.jpg";
        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("login.txt")));
        Jsonb jsonb = JsonbBuilder.create();
        while((string=reader.readLine()) != null)
        {
            userinfomation user = jsonb.fromJson(string,userinfomation.class);
            if(user.getUsername().equals(username)&&user.getPasswd().equals(password))
            {
                flag = 1;
                HttpSession session=req.getSession(true);
                Map<String,String > map = new HashMap<>();
                map.put("username",user.getUsername());
                map.put("phone",user.getPhone());
                map.put("password",user.getPasswd());
                map.put("img",user.getImg());
                session.setAttribute("USER",map);
                reader.close();
            }
            if(flag == 1) break;
        }
        if(flag == 1) resp.sendRedirect("user.jsp");
        else {
            reader.close();
            resp.sendRedirect("error.html");
        }
    }
}
